import React, { ReactElement, useContext, useEffect, useMemo } from 'react';
import { ClassRoomType } from '../../constant';
import { Store } from '../../reducer';

import {
  destroyChatRoom,
  getMessageList,
  getMessageRemindNum,
  getReplayMessageList,
  initChatRoom,
  initChatRoomProps,
  startReceiveCurrentTimeChangeMsg,
  stopReceiveCurrentTimeChangeMsg
} from './actions';
import Container from './components/Container';
import Provider from './reducer';

export default (): ReactElement => {
  const { state } = useContext(Store);
  const { type, lesson, assistantInfo, lessonStartTime } = state;
  const { lessonId } = lesson;
  const isVod = type === ClassRoomType.Vod;
  useEffect((): (() => void) => {
    if (lessonId !== -1) {
      if (!isVod) {
        initChatRoom();
      }
      initChatRoomProps({ lessonId, assistantInfo, isVod, lessonStartTime });
      const { id } = assistantInfo;
      getMessageRemindNum(lessonId, Number(id));

      if (isVod) {
        getReplayMessageList(Number(id), lessonId);
        startReceiveCurrentTimeChangeMsg();
      } else {
        getMessageList(Number(id), lessonId);
      }
    }

    return (): void => {
      destroyChatRoom();
      stopReceiveCurrentTimeChangeMsg();
    };
  }, [assistantInfo, isVod, lessonId, lessonStartTime]);
  return useMemo(
    (): ReactElement => (
      <Provider>
        <Container />
      </Provider>
    ),
    []
  );
};
